package com.zut.interceptor;


import com.alibaba.druid.filter.config.ConfigTools;
import com.zut.service.AdminService;
import com.zut.service.CoachService;
import com.zut.service.StudentService;
import com.zut.util.DataSourcePasswordUtil;
import com.zut.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    StudentService studentService;
    @Autowired
    CoachService coachService;
    @Autowired
    AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        // 如果请求不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (token != null) {
            String id = JwtUtil.getUserNameByToken(request);
            String password = studentService.getPassword(id);
            if(password == null){
                password = coachService.getPassword(id);
                        if(password == null){
                            password = adminService.getPassword(id);
                        }
            }
            // 这边拿到的 用户名 应该去数据库查询获得密码，简略，步骤在service直接获取密码
            boolean result = JwtUtil.verify(token, id, password);
            if (result) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
